package in.hitmedia.test.sort;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class InsertionSort 
{

	private Long[] read(String filename) throws IOException
	{
		
		BufferedReader br = new BufferedReader(new FileReader(filename));
		
		String line = null;
		
		List<Long> a = new ArrayList<Long>();
		while((line = br.readLine()) != null)
		{
			try
			{
				long parseLong = Long.parseLong(line.trim());
				a.add(parseLong);
			}
			catch (NumberFormatException nfe)
			{
				
			}
		}
		
		return a.toArray(new Long[a.size()]); 
	}
	
	private void exchange(Long[] a, int i, int j) 
	{
		Long tmp=a[j];
		a[j]=a[i];
		a[i]= tmp;
	}
	
	private void insertionSort1(Long a[])
	{
		for (int i=1; i < a.length; ++i)
		{
			
			for (int j=i; j > 0 && a[j-1] > a[j]; --j)
			{
				exchange(a, j-1, j);
			}

			//print(a);
		}
	}
	
	private void insertionSort2(Long a[])
	{
		for (int i=1; i < a.length; ++i)
		{
			
			for (int j=i; j > 0 && a[j-1] > a[j]; --j)
			{
				Long tmp = a[j-1];
				a[j-1]=a[j];
				a[j]=tmp;
			}

			//print(a);
		}
		
	}
	
	private void insertionSort3(Long a[])
	{
		for (int i=1; i < a.length; ++i)
		{
			long tmp = a[i];
			int j=i;
			for (j=i; j > 0 && a[j-1] > tmp; --j)
			{
				a[j] = a[j-1];
			}
			a[j] = tmp;
			//print(a);
		}
	}
	
	private static void print(Long a[])
	{
		for(int i=0; i < a.length; ++i)
		{
			System.out.print(a[i]+"\t");
			if ((i+1) %10 == 0)
			{
				System.out.println();
			}
		}
		System.out.println();
	}
	
	public void runInsertionSort (String in, String out)
	{
		try
		{
			Long[] inArray = {6L, 7L, 9L, 2L, 1L, 8L , 5L};
			//Long[] inArray = read(in);
			//print(inArray);
			
			long start = System.nanoTime();
			insertionSort1(inArray);
			long end = System.nanoTime();
			
			System.out.println("Time to process "+((end - start)) +" nanoseconds.");
			
			Long[] inArray2 = {6L, 7L, 9L, 2L, 1L, 8L , 5L};
			
			start = System.nanoTime();
			insertionSort2(inArray2);
			end = System.nanoTime();
			
			System.out.println("Time to process "+((end - start)) +" nanoseconds.");
			
			Long[] inArray3 = {6L, 7L, 9L, 2L, 1L, 8L , 5L};
			
			start = System.nanoTime();
			insertionSort3(inArray3);
			end = System.nanoTime();
			
			System.out.println("Time to process "+((end - start)) +" nanoseconds.");
			
			BufferedWriter bw = new BufferedWriter(new FileWriter(out));
			
			for (int i = 0; i < inArray.length; ++i)
			{
				bw.write(""+inArray[i]);
				bw.newLine();
			}
			bw.close();
			
			//print(inArray);
		}
		catch (Exception e)
		{
			System.out.println("Received exception"+ e);
		}
		
		
	}
	
	public static void main(String args[])
	{
		InsertionSort is = new InsertionSort();
		is.runInsertionSort(args[0], args[1]);
	}
	
}
